package com.fast.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtils {

	private static Logger logger = LoggerFactory.getLogger(DateUtils.class);

	private static final String Style_YYYY_MM_DD = "yyyyMMdd";
	private static final String STYLE_HHMMSS = "HHmmss";
	private static final String DEFAULT = Style_YYYY_MM_DD;

	public static String getCurrentDate() {
		return format(getCurrent());
	}
	
	public static String getCurrentFormateDate() {
		return format(getCurrent(),"yyyy-MM-dd");
	}

	public static String getCurrentFormateTime() {
		return format(getCurrent(),"HH:mm:ss");
	}
	
	public static String getCurrentFormateTimestamp(){
		return format(getCurrent(), "yyyy-MM-dd HH:mm:ss");
	}
	
	public static String getCurrentTimestamp(){
		return format(getCurrent(), "yyyyMMddHHmmss");
	}
	
	private static Date getCurrent() {
		return new Date();
	}

	public static String getCurrentTime() {
		return format(getCurrent(), STYLE_HHMMSS);
	}

	
	public static Date toDate(String str, String pattern) {

		SimpleDateFormat sdf = getInstance(pattern);
		Date date = null;
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			logger.error("", e);
		}
		return date;

	}

	private static SimpleDateFormat getInstance(String pattern) {
		if (StringUtils.isEmpty(pattern)) {
			pattern = DEFAULT;
		}
		SimpleDateFormat sdf = null;
		if (sdf == null) {
			sdf = new SimpleDateFormat(pattern);
		}
		return sdf;
	}

	public static String format(Date date) {
		return format(date, Style_YYYY_MM_DD);
	}

	public static String format(Date date, String pattern) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = getInstance(pattern);
		return sdf.format(date);
	}

	public static String subYearToString(Date date, int year) {
		SimpleDateFormat sdf = getInstance(DEFAULT);
		return sdf.format(subYear(date, year));
	}

	public static Date subYear(Date date, int year) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, year);
		return cal.getTime();
	}

	public static void main(String[] args) {
		System.out.println(subYearToString(new Date(), -1));
	}
}
